package com.kit.sm;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.kit.ByteUtil;

public class SM4Util {

	static {
		Security.addProvider(new BouncyCastleProvider());
	}

	static String key = "1234567890123456"; // aes 密钥key ：must be 16
	public static void main(String[] args) throws Exception {

		// for (int i = 0; i < 3; i++)
		// key += key;
		System.err.println(key.length());
		String data = "06060000007E03F5FF61FCF2FFE0DA1B00021D0E";
		System.out.println(data.length());

		for (int i = 0; i < 10; i++) {
			System.out.println("明文长度[" + ByteUtil.hex2byte(data).length + "]");
			byte[] pwd = encrypt(data);
			if (pwd == null)
				break;
			System.out.println("密文长度[" + pwd.length + "]");
			byte[] res = decrypt(pwd);
			if (res == null)
				break;
			System.out.println("解密明文[" + res.length + "]\t" + i);
			System.out.println(ByteUtil.byte2hex(res));
			Thread.sleep(100);
		}
	}

	public static byte[] encrypt(String hexSrc) {
		try {
			if (key == null || key.length() != 16)
				throw new Exception("key不满足条件");
			byte[] raw = key.getBytes();
			Key sm4Key = new SecretKeySpec(raw, "SM4");
			Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", BouncyCastleProvider.PROVIDER_NAME);
			cipher.init(Cipher.ENCRYPT_MODE, sm4Key);
			return cipher.doFinal(ByteUtil.hex2byte(hexSrc));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static byte[] decrypt(byte[] src) {
		try {
			if (key == null || key.length() != 16)
				throw new Exception("key不满足条件");
			byte[] raw = key.getBytes();
			Key sm4Key = new SecretKeySpec(raw, "SM4");
			Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", BouncyCastleProvider.PROVIDER_NAME);
			// IvParameterSpec iv = new IvParameterSpec(key.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, sm4Key);
			return cipher.doFinal(src);
		} catch (Exception e) {
			return null;
		}
	}
}
